package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName StorageTccActionImpl
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/7/2 15:57
 * @Version V1.0
 **/
@Component
public class StorageTccActionImpl implements StorageTccAction{
    @Autowired
    private StorageMapper storageMapper;
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
        Storage storage = storageMapper.selectById(productId);
        if (storage.getResidue()<count){
            throw new RuntimeException("库存不足");
        }
        //可用->冻结
        storageMapper.updateResidueToFrozen(productId, count);
        //第一阶段成功,保存一个一阶段的成功标记
        ResultHolder.setResult(StorageTccAction.class, ctx.getXid(), "p");
        return true;
    }
    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        //如果没有标记,二阶段不执行
        //第一阶段没有成功或者第二阶段已执行过,标记已删除,不再重复执行
        if (ResultHolder.getResult(StorageTccAction.class, ctx.getXid())==null){
            return true;
        }
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        //冻结->已使用
        storageMapper.updateFrozenToUsed(productId, count);
        //第二阶段成功-提交成功,删除标记
        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(StorageTccAction.class, ctx.getXid())==null){
            return true;
        }
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        //冻结->已使用
        storageMapper.updateFrozenToResidue(productId, count);
        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }
}
